import React, { useState, useCallback } from 'react';
import { Upload, Trash2, Plus } from 'lucide-react';

interface ImageUploaderProps {
  images: string[];
  onChange: (images: string[]) => void;
  maxImages?: number;
}

const ImageUploader: React.FC<ImageUploaderProps> = ({ 
  images, 
  onChange, 
  maxImages = 5 
}) => {
  const [isDragging, setIsDragging] = useState(false);
  const [showUrlInput, setShowUrlInput] = useState(false);
  const [urlInputValue, setUrlInputValue] = useState('');

  // 处理图片上传
  const handleImageUpload = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (!files) return;

    const processFile = (file: File) => {
      return new Promise<string>((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => {
          const result = reader.result as string;
          resolve(result);
        };
        reader.onerror = reject;
        reader.readAsDataURL(file);
      });
    };

    const uploadPromises = Array.from(files).map(processFile);

    Promise.all(uploadPromises)
      .then((newImages) => {
        const updatedImages = [...images, ...newImages].slice(0, maxImages);
        onChange(updatedImages);
      })
      .catch((error) => {
        console.error('图片上传失败:', error);
      });
  }, [images, onChange, maxImages]);

  // 处理拖拽事件
  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(true);
  }, []);

  const handleDragLeave = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
  }, []);

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
    const files = e.dataTransfer.files;
    if (!files) return;

    const imageFiles = Array.from(files).filter(file => file.type.startsWith('image/'));
    if (imageFiles.length === 0) return;

    const processFile = (file: File) => {
      return new Promise<string>((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => {
          const result = reader.result as string;
          resolve(result);
        };
        reader.onerror = reject;
        reader.readAsDataURL(file);
      });
    };

    const uploadPromises = imageFiles.map(processFile);

    Promise.all(uploadPromises)
      .then((newImages) => {
        const updatedImages = [...images, ...newImages].slice(0, maxImages);
        onChange(updatedImages);
      })
      .catch((error) => {
        console.error('图片上传失败:', error);
      });
  }, [images, onChange, maxImages]);

  // 删除图片
  const handleRemoveImage = useCallback((index: number) => {
    const updatedImages = images.filter((_, i) => i !== index);
    onChange(updatedImages);
  }, [images, onChange]);

  // 添加图片
  const handleAddImage = useCallback(() => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/*';
    input.multiple = true;
    input.onchange = handleImageUpload;
    input.click();
  }, [handleImageUpload]);

  // 处理URL输入
  const handleUrlSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (urlInputValue.trim() && images.length < maxImages) {
      const updatedImages = [...images, urlInputValue.trim()];
      onChange(updatedImages);
      setUrlInputValue('');
      setShowUrlInput(false);
    }
  };

  return (
    <div className="space-y-4">
      {/* 图片预览 */}
      {images.length > 0 && (
        <div className="grid grid-cols-3 gap-4">
          {images.map((image, index) => (
            <div key={index} className="relative group">
              <div className="aspect-square bg-gray-100 rounded-lg overflow-hidden border-2 border-gray-300">
                <img 
                  src={image} 
                  alt={`Preview ${index + 1}`} 
                  className="w-full h-full object-cover"
                />
              </div>
              <button
                type="button"
                onClick={() => handleRemoveImage(index)}
                className="absolute -top-3 -right-3 bg-red-500 text-white p-1.5 rounded-full shadow-lg hover:bg-red-600 transition-colors opacity-0 group-hover:opacity-100"
                aria-label="删除图片"
              >
                <Trash2 size={16} />
              </button>
            </div>
          ))}
        </div>
      )}

      {/* 图片添加选项 */}
      {images.length < maxImages && (
        <div className="space-y-4">
          {/* URL输入区域 */}
          {showUrlInput ? (
            <form onSubmit={handleUrlSubmit} className="flex gap-2">
              <input
                type="url"
                value={urlInputValue}
                onChange={(e) => setUrlInputValue(e.target.value)}
                placeholder="输入图片URL"
                className="flex-1 border border-gray-300 rounded-md p-3 focus:ring-2 focus:ring-brand-orange focus:border-brand-orange focus:outline-none"
                required
              />
              <button
                type="submit"
                className="bg-brand-orange text-white px-4 py-2 rounded-md hover:bg-orange-600 transition-colors font-medium"
              >
                添加
              </button>
              <button
                type="button"
                onClick={() => setShowUrlInput(false)}
                className="bg-gray-200 text-gray-800 px-4 py-2 rounded-md hover:bg-gray-300 transition-colors font-medium"
              >
                取消
              </button>
            </form>
          ) : (
            <div className="flex gap-4">
              {/* 本地上传区域 */}
              <div
                className={`flex-1 border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-all ${isDragging 
                  ? 'border-brand-orange bg-brand-orange/10' 
                  : 'border-gray-300 hover:border-brand-orange hover:bg-brand-cream'}`}
                onDragOver={handleDragOver}
                onDragLeave={handleDragLeave}
                onDrop={handleDrop}
              >
                <input
                  type="file"
                  accept="image/*"
                  multiple
                  onChange={handleImageUpload}
                  className="hidden"
                  id="image-upload"
                />
                <label htmlFor="image-upload" className="cursor-pointer w-full h-full flex items-center justify-center">
                  <div className="flex flex-col items-center justify-center gap-3">
                    <div className="w-12 h-12 rounded-full bg-brand-orange/20 flex items-center justify-center">
                      <Upload size={24} className="text-brand-orange" />
                    </div>
                    <div>
                      <p className="font-medium text-brand-wood">上传本地图片</p>
                      <p className="text-sm text-gray-500 mt-1">点击或拖拽图片到此处</p>
                    </div>
                  </div>
                </label>
              </div>

              {/* URL添加按钮 */}
              <div
                className="flex-1 border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-all border-gray-300 hover:border-brand-orange hover:bg-brand-cream"
                onClick={() => setShowUrlInput(true)}
              >
                <div className="flex flex-col items-center justify-center gap-3">
                  <div className="w-12 h-12 rounded-full bg-brand-orange/20 flex items-center justify-center">
                    <Plus size={24} className="text-brand-orange" />
                  </div>
                  <div>
                    <p className="font-medium text-brand-wood">添加图片URL</p>
                    <p className="text-sm text-gray-500 mt-1">输入网络图片链接</p>
                  </div>
                </div>
              </div>
            </div>
          )}

          <div className="text-center text-sm text-gray-500">
            已上传 {images.length}/{maxImages} 张，最多可上传 {maxImages} 张
          </div>
        </div>
      )}
    </div>
  );
};

export default ImageUploader;
